package com.be.beadmin.service.controller;

import com.alibaba.excel.EasyExcel;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.service.dto.input.DictionaryDto;
import com.be.beadmin.service.dto.output.DictionaryEx;
import com.be.beadmin.service.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
* @author chenwei
* @date 2023-02-02
**/
@RestController
public class DictionaryController {

    @Autowired
    private  DictionaryService dictionaryService;


    @PostMapping(value = "/system/getDictionaryByPage")
    public ResultModel getDictionaryByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(dictionaryService.getDictionaryByPage(pageEntity)) ;
    }

    @PostMapping("/system/addDictionary")
    public ResultModel addDictionary(@RequestBody DictionaryDto dictionaryDto){
        dictionaryService.addDictionary(dictionaryDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/system/delDictionary")
    public ResultModel delDictionary(@RequestBody DictionaryDto dictionaryDto){
        dictionaryService.delDictionary(dictionaryDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/system/updateDictionary")
    public ResultModel updateDictionary(@RequestBody DictionaryDto dictionaryDto){
        dictionaryService.updateDictionary(dictionaryDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/system/exportDictionary")
    public void exportDictionary(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<DictionaryEx> dictionaryPage = dictionaryService.getDictionaryByPage(pageEntity);
        List<DictionaryEx> dictionaryExes = dictionaryPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Dictionary接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DictionaryEx.class).sheet("sheet1").doWrite(dictionaryExes);
    }
}